package com.zmytest.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zmytest.dto.AccountDto;
import com.zmytest.util.Encryptor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.util.ObjectUtils;

import javax.persistence.*;
import java.util.List;

/**
 * Created on 2018/12/19.
 *  账户
 * @author zhangmingyu
 */
@Entity
@EqualsAndHashCode(callSuper = true)
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
@Data
public class Account extends BaseModel<Long>{

    private String name;

    private String password;

    private Long userId;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "userId",insertable = false,updatable = false)
    private User user;

    @ManyToMany
    @JoinTable(
            name = "account_role",
            joinColumns = {@JoinColumn(name = "account_id")},
            inverseJoinColumns = {@JoinColumn(name = "role_id")}
    )
    private List<Role> roles;

    public Account(){}

    public Account(AccountDto accountDto,List<Role> roles){
        this.name = accountDto.getName();
        this.password = Encryptor.getSHACode(accountDto.getPassword());
        this.userId = accountDto.getUserId();
        this.roles = roles;
    }

    public void update(AccountDto accountDto,List<Role> roles) {
        this.name = ObjectUtils.isEmpty(accountDto.getName())? this.name:accountDto.getName();
        this.password = ObjectUtils.isEmpty(accountDto.getPassword())? this.password:accountDto.getPassword();
        this.userId = ObjectUtils.isEmpty(accountDto.getUserId())? this.userId:accountDto.getUserId();
        this.roles = roles;
    }

    /**
     * 判断是否有权限
     * @param accessiblePermissionNames 可访问的权限名称
     * @return boolean
     */
    public boolean hasPermission(String... accessiblePermissionNames){
        for (Role role : this.roles) {
            for (Permission permission : role.getPermissions()) {
                for (String accessiblePermissionName : accessiblePermissionNames) {
                    if (accessiblePermissionName.equals(permission.getName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}